<?php
/**
 * Login_Acl
 *
 * @author Renato Innocenti 
 * @todo "Fazer um programa para instalar modulos."
 */
class Mylibrary_Myacl_Acl extends Zend_Acl {
    /**
     * __construct
     *
     * @param Zend_Db_Adapter $db
     * @param integer $role
     */
    public function __construct($role) {
        $this->loadRoles();
        $this->loadResources();
        $this->loadPermissions($role);
       
    }
    /**
     * Load all the roles from the DB
     *
     * @param Zend_Db_Adapter $db
     * @return boolean
     */
    public function loadRoles() {
    	$mapper = new Usuarios_Model_PerfilMapper();
    	$allrules = $mapper->fetchAll();
    	foreach ($allrules as $role){
    		if(!empty($role->id_parent)|| $role->id_parent !== 0){
    			$this->addRole(new Zend_Acl_Role($role->id),$role->id_parent);
    		}else{
    			$this->addRole(new Zend_Acl_Role($role->id));
    		}
    	}
    	return true;
    }
    /**
     * Load all the resources for the specified role
     *
     * @param Zend_Db_Adapter $db
     * @param integer $role
     * @return boolean
     */
    public function loadResources() {
    	#$resources= new Login_Model_Resources($db);
    	$resources= new Recursos_Model_RecursosMapper;
    	$allResources = $resources->fetchAll();
    	#$allResources= $resources->getResources($role);
    	foreach ($allResources as $res) {
                if (!$this->has($res->getRecurso())) {
                    $this->addResource(new Zend_Acl_Resource($res->getRecurso()));
                }
    	}
        return true;
    }
    /**
     * Load all the permission for the specified role
     *
     * @param Zend_Db_Adapter $db
     * @param integer $role
     * @return boolean
     */
    public function loadPermissions($role) {
    	$permissions = new Recursos_Model_PermissaoMapper();
    	$allPermissions = $permissions->findperfil($role);
    	#return true;
    	if($allPermissions != true){
    		$this->allow($role,"*/*/*");	
    	}else{   		
    		foreach ($allPermissions as $permissao) {
    			if ($permissao['permissao']->permissao =='allow') {
    				$this->allow($role,$permissao['recurso']->recurso);
    			} else {
    				$this->deny($role,$permissao['recurso']->recurso);
    			}
    		}
    	}
    	return true;
    }

}
